package pl.mchaniewski.ryneczek.services.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pl.mchaniewski.ryneczek.dao.CompanyDao;
import pl.mchaniewski.ryneczek.pojo.Company;
import pl.mchaniewski.ryneczek.services.CompanyService;

@Service("companyService")
public class CompanyServiceImpl implements CompanyService {
    private static final Logger logger = LoggerFactory
            .getLogger(CompanyServiceImpl.class);
    private CompanyDao companyDao;

    @Autowired
    public void setCompanyDao(CompanyDao companyDao) {
        this.companyDao = companyDao;
    }

    @Override
    public Company save(Company entity) {
        try {
            return companyDao.save(entity);
        } catch (Exception ex) {
            logger.error("Exception: {}", ex.getMessage());

            return null;
        }
    }

    @Override
    public List<Company> findAll() {
        try {
            return companyDao.loadAll();
        } catch (Exception ex) {
            logger.error("Exception: {}", ex.getMessage());

            return null;
        }
    }

    @Override
    public Company findByName(String name) {
        List<Company> companyList;
        try {
            companyList = companyDao.findByName(name);
        } catch (Exception ex) {
            logger.error("Exception: {}", ex.getMessage());

            return null;
        }

        if (companyList == null || companyList.size() == 0) {
            return null;
        }

        if (companyList.size() > 1) {
            logger.warn("Two or more companies with same name! Name: {})",
                    companyList.get(0).getName());
        }

        return companyList.get(0);
    }

}
